package client;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;


/**
 * @author Rob
 *
 */
public class ListJoiner extends Observable implements Observer {

	private Comparable[][] sortedLists;
	private int sortParts;
	private SorterThread sorterThread;
	private ArrayList<Comparable>[] listHelper;
	private int countLists;
	private int countNumbers;
	
	/**
	 * Initialize the class.
	 * @param sortParts
	 */
	public ListJoiner(int sortParts) {
		this.sortParts = sortParts;
		sortedLists = new Comparable[sortParts][];
		listHelper = new ArrayList[sortParts];
	}
	
	/**
	 * Put the list in the collection of lists. When they are all done. sort it.
	 * @param arg0 The observable object
	 * @param arg1 The message that the observable object gives.
	 */
	@Override
	public synchronized  void update(Observable arg0, Object arg1) {
		if(arg1 == "List is sorted"){
			//get sorterThread and take the values/objects you need
			sorterThread = (SorterThread) arg0;
			Comparable[] sortedList = sorterThread.getSortedList();
			listHelper[sorterThread.getVolgNummer()] = new ArrayList<Comparable>(); 
			int testint = sortedList.length;
			//put values in array for easy storage
			for(int i = 0; i< testint; i++) {
				listHelper[sorterThread.getVolgNummer()].add(sortedList[i]);
			}
			//put array in the collection of Lists
			sortedLists[sorterThread.getVolgNummer()] = (Comparable[]) listHelper[sorterThread.getVolgNummer()].toArray(new Comparable[listHelper[sorterThread.getVolgNummer()].size()]);
			//count stuff for the join
			countLists++;	
			countNumbers += sortedLists[sorterThread.getVolgNummer()].length;
		} 
		//check if all threads are done
		if(countLists == sortParts) {
			this.join(sortedLists, (countNumbers));
		}
	}

	/**
	 * Join the lists together in 1 list.
	 * @param lists 	All the seperate lists that need to be merged together.
	 * @param amountOfNumbers	The amount of numbers to join together
	 * @return sortedList	The new sorted list.
	 */
	public Comparable[] join(Comparable[][] lists, int amountOfNumbers) {
		Comparable[] sortedList = new Comparable[amountOfNumbers];
		int placeInList = 0;
		for(Comparable[] lst : lists) {
			for(int a = 0; a < lst.length; a++){
				sortedList[placeInList] = lst[a];
				placeInList++;
			}
		}
		//print the final sorted list in console
		for(int i = 0; i<sortedList.length;i++) {
			System.out.println((i+1)+" : "+sortedList[i]);
		}
		return sortedList;
	}
}